package com.meihua.baoleyi.widget;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;

import com.meihua.baoleyi.R;


/**
 * @author chengs
 * @PackageName: com.handongkeji.widget
 * @Create 2016/2/2 9:38
 * @Site http://www.handongkeji.com
 * @Copyrights 2016/1/28 handongkeji All rights reserved.
 */
public class NoEmojiEditText extends EditText implements
		View.OnFocusChangeListener, TextWatcher {

	/**
	 * 删除按钮的引用
	 */
	private Drawable mClearDrawable;
	/**
	 * 控件是否有焦点
	 */
	private boolean hasFoucs;
	private Context mContext;
	private int cursorPos;
	private String inputAfterText;
	private boolean resetText;

	public NoEmojiEditText(Context context) {
		this(context, null);
	}

	public NoEmojiEditText(Context context, AttributeSet attrs) {
		this(context, attrs, android.R.attr.editTextStyle);
	}

	public NoEmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		this.mContext = context;
		init();
	}

	private void init() {
		// 获取EditText的DrawableRight,假如没有设置我们就使用默认的图片
		mClearDrawable = getCompoundDrawables()[2];
		if (mClearDrawable == null)
			// throw new
			// NullPointerException("You can add drawableRight attribute in XML");
			mClearDrawable = getResources().getDrawable(
					R.drawable.edittext_background_selector);
		mClearDrawable.setBounds(0, 0, mClearDrawable.getIntrinsicWidth(),
				mClearDrawable.getIntrinsicHeight());
		setClearIconVisible(false);
		setOnFocusChangeListener(this);
		addTextChangedListener(this);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			if (getCompoundDrawables()[2] != null) {
				boolean touchable = event.getX() > (getWidth() - getTotalPaddingRight())
						&& (event.getX() < ((getWidth() - getPaddingRight())));
				if (touchable)
					this.setText("");
			}
		}
		return super.onTouchEvent(event);
	}

	Handler mHandler = new Handler();

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		this.hasFoucs = hasFocus;
		if (hasFocus)
			setClearIconVisible(getText().length() > 0);
		else
			setClearIconVisible(false);

	}

	protected void setClearIconVisible(boolean visible) {
		Drawable right = visible ? mClearDrawable : null;
		setCompoundDrawables(getCompoundDrawables()[0],
				getCompoundDrawables()[1], right, getCompoundDrawables()[3]);
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {
		if (!resetText) {
			cursorPos = getSelectionEnd();
			inputAfterText = s.toString();
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		
		if (!resetText) {
			if (cursorPos > s.length()) {
				return;
			}
				CharSequence input = s.subSequence(cursorPos, s.length());
				if (!checkIsValid(input.toString())) {
					resetText = true;
					setText(inputAfterText);
//					setAnimation();
					CharSequence text = getText();
					if (text instanceof Spannable) {
						Spannable spanText = (Spannable) text;
						Selection.setSelection(spanText, spanText.length());
					}
				}
			} else{
			resetText = false;
			}
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int lengthBefore,
                              int lengthAfter) {
//		if (hasFoucs)
//			setClearIconVisible(s.length() > 0);
	}

	public void setAnimation() {
		this.setAnimation(shakeAnimation(5));
	}

	public Animation shakeAnimation(int count) {
		TranslateAnimation translateAnimation = new TranslateAnimation(0, 10,
				0, 0);
		translateAnimation.setInterpolator(new CycleInterpolator(count));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

	private boolean checkIsValid(String source) {
		return isChinese(source) || isEn(source);
	}

	public boolean isChinese(String strName) {
		char[] ch = strName.toCharArray();
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			if (isChinese(c)) {
				return true;
			}
		}
		return false;
	}

	private boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
			return true;
		}
		return false;
	}

	private boolean isEn(String source) {
		return source.matches("^[a-zA-Z0-9\\s]");
	}

	public boolean containsEmoji(String source) {
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (!isEmojiCharacter(codePoint)) {
				return true;
			}
		}
		return false;
	}

	private boolean isEmojiCharacter(char codePoint) {
		int b = codePoint;
		return (codePoint == 0x0)
				|| (codePoint == 0x9)
				|| (codePoint == 0xA)
				|| (codePoint == 0xD)
				|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF) && (codePoint != 0x263a))
				|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

}
